package com.example.administrator.x3picturetransliteration.Home.Activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import android.support.v4.content.FileProvider;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.example.administrator.x3picturetransliteration.Base.BaseActivity;
import com.example.administrator.x3picturetransliteration.Base.BasePresenter;
import com.example.administrator.x3picturetransliteration.Bean.AppChannelBean;
import com.example.administrator.x3picturetransliteration.Constants;
import com.example.administrator.x3picturetransliteration.Home.Fragment.FileFragment;
import com.example.administrator.x3picturetransliteration.Home.Fragment.MeFragment;
import com.example.administrator.x3picturetransliteration.Home.Fragment.NavigationFragment;
import com.example.administrator.x3picturetransliteration.Home.Presenter.Activity.AppPresenter;
import com.example.administrator.x3picturetransliteration.Home.Presenter.Fragment.NavigationPresenter;
import com.example.administrator.x3picturetransliteration.R;
import com.example.administrator.x3picturetransliteration.RxBus;
import com.example.administrator.x3picturetransliteration.Util.Loading2DialogUtil;
import com.example.administrator.x3picturetransliteration.Util.MediaUtil;
import com.example.administrator.x3picturetransliteration.Util.ToastUtil;
import com.muzhi.camerasdk.FilterImageActivity;
import com.muzhi.camerasdk.model.CameraSdkParameterInfo;
import com.muzhi.camerasdk.utils.AppUtils;
import com.muzhi.camerasdk.utils.FileUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;
import rx.Observer;

/**
 * 首页
 * Created by Administrator on 2019/8/16.
 */

@RuntimePermissions
public class AppActivity extends BaseActivity{

    @BindView(R.id.MeViewPage)ViewPager MeViewPage;

    @BindViews({R.id.DistinguishImg,R.id.FileImg,R.id.MeImg})ImageView[] imgs;
    @BindViews({R.id.DistinguishText,R.id.FileText,R.id.MeText})TextView[] texts;

    private Camera mCamera;

    private File mTmpFile;
    private ArrayList<String> resultList = new ArrayList<>();

    private List<Fragment> fragments = new ArrayList<>();

    private AppPresenter mAppPresenter;
    private NavigationPresenter mNavigationPresenter;

    @Override
    public int intiLayout() {
        return R.layout.home_activity_app;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        fragments.add(new NavigationFragment());
        fragments.add(new FileFragment());
        fragments.add(new MeFragment());

        MeViewPage.setOffscreenPageLimit(3);

        MeViewPage.setAdapter(new meAdapter(getSupportFragmentManager()));

        mAppPresenter = new AppPresenter(this,mCompositeSubscriptions);
        mNavigationPresenter = new NavigationPresenter(this,mCompositeSubscriptions);

        RxBus.getInstance().Register(AppActivity.class, new Observer<Object>() {


            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(Object o) {

                try{

                    if ("work".equals(o + "")){

                        Style(1);
                        return;
                    }

                    Map<String,Object> map = (Map<String, Object>)JSON.parse(o+"");

                    Map<String,String> httpdata = new HashMap<>();

                    for (String key:map.keySet())httpdata.put(key,map.get(key) + "");

                    mAppPresenter.saveTemp(httpdata);

                }catch (Exception e){

                }

            }
        });

    }

    @Override
    protected void onDestroy() {

        RxBus.getInstance().Cancellation(AppActivity.class);

        super.onDestroy();
    }

    /** 切换页卡 */
    @OnClick({R.id.DistinguishView,R.id.FileView,R.id.MeView})
    public void StyleClick(View view){

        switch (view.getId()){

            case R.id.DistinguishView:

                Style(0);
                break;

            case R.id.FileView:

                Style(1);
                break;

            case R.id.MeView:

                Style(2);
                break;

        }
    }

    private void Style(int x){

        imgs[0].setImageResource(R.mipmap.home_shibie);
        imgs[1].setImageResource(R.mipmap.home_wendang);
        imgs[2].setImageResource(R.mipmap.home_wode);

        texts[0].setTextColor(getResources().getColor(R.color.HomeActivityAppText2));
        texts[1].setTextColor(getResources().getColor(R.color.HomeActivityAppText2));
        texts[2].setTextColor(getResources().getColor(R.color.HomeActivityAppText2));

        switch (x){

            case 0:

                imgs[x].setImageResource(R.mipmap.home_shibie2);
                break;

            case 1:

                imgs[x].setImageResource(R.mipmap.home_wendang2);
                break;

            case 2:

                imgs[x].setImageResource(R.mipmap.home_wode2);
                break;

        }

        texts[x].setTextColor(getResources().getColor(R.color.HomeActivityAppText1));

        fragments.get(x).onHiddenChanged(false);

        MeViewPage.setCurrentItem(x);

    }

    private class meAdapter extends FragmentPagerAdapter {

        public meAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }
    }

    /** 选择图片返回结果 */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {

        //if (data==null)return;

        if (requestCode == CameraSdkParameterInfo.TAKE_PICTURE_FROM_GALLERY) {

            if(data!=null){

                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        sleep();
                        AppActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                tpsb(data);
                            }
                        });
                    }
                }).start();
            }
        }

        if (requestCode == 2048){

            if(data!=null){

                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        sleep();
                        AppActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                fy(data);
                            }
                        });
                    }
                }).start();
            }

        }

        if (requestCode == 4096){

            if(data!=null) {

                CameraSdkParameterInfo mCameraSdkParameterInfo=(CameraSdkParameterInfo)data.getExtras().getSerializable(CameraSdkParameterInfo.EXTRA_PARAMETER);

                mCamera.getImg(mCameraSdkParameterInfo);

            }

        }

        // 相机拍照完成后，返回图片路径
        if(requestCode == CameraSdkParameterInfo.TAKE_PICTURE_FROM_CAMERA){
            if(resultCode == Activity.RESULT_OK) {

                resultList.clear();
                resultList.add(mTmpFile.getPath());

                selectComplate();

            }
        }
    }

    /**
     * 选择相机
     */
    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA})
    public void showCameraAction(Camera mCamera) {

        this.mCamera = mCamera;

        // 跳转到系统照相机
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if(cameraIntent.resolveActivity(this.getPackageManager()) != null){
            // 设置系统相机拍照后的输出路径
            // 创建临时文件
            mTmpFile = FileUtils.createTmpFile(this);
            Uri imageUri;
            if (Build.VERSION.SDK_INT >= 24) {
                String providerPkg= AppUtils.getAppPackageName(this)+".fileprovider";
                imageUri = FileProvider.getUriForFile(this,providerPkg , mTmpFile);//通过FileProvider创建一个content类型的Uri
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);//将拍取的照片保存到指定URI
                cameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
                cameraIntent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);//增加读写权限
            }
            else {
                imageUri=Uri.fromFile(mTmpFile);
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);//将拍取的照片保存到指定URI
            }

            startActivityForResult(cameraIntent, CameraSdkParameterInfo.TAKE_PICTURE_FROM_CAMERA);

        }else{
            new ToastUtil(this).getToast(false,"没有系统相机").show();
        }
    }

    public void showCameraActionsts(Camera mCamera){

        AppActivityPermissionsDispatcher.showCameraActionWithCheck(this,mCamera);
    }

    //选择完成实现跳转
    private void selectComplate(){

        CameraSdkParameterInfo mCameraSdkParameterInfo = new CameraSdkParameterInfo();

        mCameraSdkParameterInfo.setImage_list(resultList);
        Bundle b=new Bundle();
        b.putSerializable(CameraSdkParameterInfo.EXTRA_PARAMETER, mCameraSdkParameterInfo);

        Intent intent = new Intent();
        intent.putExtras(b);

        intent = new Intent(this, FilterImageActivity.class);
        intent.putExtras(b);
        startActivityForResult(intent, 4096);

    }

    public interface Camera{

        public void getImg(CameraSdkParameterInfo mCameraSdkParameterInfo);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // NOTE: delegate the permission handling to generated method
        AppActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    /** 图片识别 */
    public void tpsb(final Intent data){

        CameraSdkParameterInfo mCameraSdkParameterInfo=(CameraSdkParameterInfo)data.getExtras().getSerializable(CameraSdkParameterInfo.EXTRA_PARAMETER);
        final List<String> list = new ArrayList<>();
        list.addAll(mCameraSdkParameterInfo.getImage_list());

        mNavigationPresenter.app_channel(new BasePresenter.Callback() {
            @Override
            public void getData(Object qdata) {

                AppChannelBean mAppChannelBean = (AppChannelBean)qdata;

                if (!"0".equals(Constants.getConstants().getmUserDataBean().getVipType()) || mAppChannelBean.getStatus()==0){

                    RecognitionResultsActivity.startRecognitionResultsActivity(AppActivity.this, JSON.toJSONString(list),data.getStringExtra("type"));

                }else {

                    new ToastUtil(AppActivity.this).getToast(false,"请先购买VIP").show();
                    startActivity(new Intent(AppActivity.this,BuyingMembersActivity.class));
                }
            }
        });
    }

    /** 翻译 */
    public void fy(final Intent data){

        CameraSdkParameterInfo mCameraSdkParameterInfo=(CameraSdkParameterInfo)data.getExtras().getSerializable(CameraSdkParameterInfo.EXTRA_PARAMETER);

        mAppPresenter.document(mCameraSdkParameterInfo.getImage_list(), new BasePresenter.Callback() {
            @Override
            public void getData(final Object data) {

                Map<String,String> map = (Map<String,String>)data;

                final String imgs = map.get("imgs");
                final String result = map.get("result");

                mNavigationPresenter.app_channel(new BasePresenter.Callback() {
                    @Override
                    public void getData(Object qdata) {

                        AppChannelBean mAppChannelBean = (AppChannelBean)qdata;

                        if (!"0".equals(Constants.getConstants().getmUserDataBean().getVipType()) || mAppChannelBean.getStatus()==0){

                            TranslateActivity.startTranslateActivity(AppActivity.this,imgs,result);

                        }else {

                            File file = new File(imgs);
                            MediaUtil.updateFileFromDatabase(AppActivity.this,file);
                            new ToastUtil(AppActivity.this).getToast(false,"请先购买VIP").show();
                            startActivity(new Intent(AppActivity.this,BuyingMembersActivity.class));
                        }
                    }
                });


            }
        });
    }

    public void sleep(){

        AppActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {

                Loading2DialogUtil.getInstance(AppActivity.this).show2();
            }
        });

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        AppActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {

                Loading2DialogUtil.getInstance(AppActivity.this).dismiss2();
            }
        });
    }
}
